const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 获取题库列表
router.get('/questions', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM exam_questions ORDER BY id DESC');
    // options 字段转为数组
    const questions = rows.map(q => ({
      ...q,
      options: q.options ? JSON.parse(q.options) : [],
      answer: q.answer ? JSON.parse(q.answer) : null
    }));
    res.json({ questions });
  } catch (err) {
    res.status(500).json({ message: '数据库查询失败', error: err.message });
  }
});

// 新增题目
router.post('/questions', async (req, res) => {
  try {
    const { type, title, description, options, answer } = req.body;
    const optionsStr = options ? JSON.stringify(options) : null;
    const answerStr = answer ? JSON.stringify(answer) : null;
    const [result] = await pool.query(
      'INSERT INTO exam_questions (type, title, description, options, answer, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())',
      [type, title, description, optionsStr, answerStr]
    );
    res.status(201).json({ message: '题目添加成功', question: { id: result.insertId, type, title, description, options, answer } });
  } catch (err) {
    res.status(500).json({ message: '添加失败', error: err.message });
  }
});

// 更新题目
router.put('/questions/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const { type, title, description, options, answer } = req.body;
    const optionsStr = options ? JSON.stringify(options) : null;
    const answerStr = answer ? JSON.stringify(answer) : null;
    const [result] = await pool.query(
      'UPDATE exam_questions SET type=?, title=?, description=?, options=?, answer=?, updated_at=NOW() WHERE id=?',
      [type, title, description, optionsStr, answerStr, id]
    );
    if (result.affectedRows === 0) return res.status(404).json({ message: '题目不存在' });
    res.json({ message: '题目更新成功' });
  } catch (err) {
    res.status(500).json({ message: '更新失败', error: err.message });
  }
});

// 删除题目
router.delete('/questions/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const [result] = await pool.query('DELETE FROM exam_questions WHERE id=?', [id]);
    if (result.affectedRows === 0) return res.status(404).json({ message: '题目不存在' });
    res.json({ message: `题目 ${id} 删除成功` });
  } catch (err) {
    res.status(500).json({ message: '删除失败', error: err.message });
  }
});

// 开始考试
router.post('/start', (req, res) => {
  const { duration, questionCount, questionTypes } = req.body;
  res.json({
    examId: Date.now(),
    questions: [],
    duration,
    startTime: new Date().toISOString()
  });
});

// 提交考试
router.post('/submit', (req, res) => {
  const { examId, answers } = req.body;
  res.json({
    message: '考试提交成功',
    score: 85,
    analysis: {
      correct: 17,
      wrong: 3,
      total: 20
    }
  });
});

module.exports = router; 